package kstech.com.wifitest.activity;

import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import J1939.J1939_Context;
import J1939.J1939_Task;
import J1939.can_Message_ts;
import kstech.com.wifitest.Point;
import kstech.com.wifitest.R;
import kstech.com.wifitest.communication.CommunicationWorker;
import kstech.com.wifitest.listener.BatteryListener;
import kstech.com.wifitest.listener.ItemDataListener;
import kstech.com.wifitest.service.DialogAsyncTask;
import kstech.com.wifitest.utils.AppContext;
import kstech.com.wifitest.utils.BitmapUtil;
import kstech.com.wifitest.utils.BitmapUtils;
import kstech.com.wifitest.utils.DialogUtil;


public class DataCollectActivity extends AppCompatActivity implements View.OnClickListener,ItemDataListener,BatteryListener {
    //1939相关
    private J1939_Task j1939ProtTask;
    private CommunicationWorker j1939CommTask;
    private ImageView imageView;
    private Button btnStart;
    private Button btnStop;
    private Button btnSave;
    private Button btnShow;
    private TextView battery;
    private LineData lineData;
    private List<Entry> entries;
    private List<Entry> entries2;
    private LineDataSet dataset;
    private LineDataSet dataset2;

    private List<Float> buffer1;
    private List<Float> buffer2;

    private List<Float> values1;
    private List<Float> values2;

    private List<Point> bufferP;
    private List<Point> bufferP2;

    private List<Point> valuesP;
    private List<Point> valuesP2;

    private int DATA1 = 1;
    private int DATA2 = 2;

    private int x = 1;
    private int x2 = 1;

    private boolean isCollecting = false;

    private DialogAsyncTask dialogAsyncTask;
    private AnimationDrawable animationDrawable;

//    public Handler handler = new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what){
//                case 1:
//                    float dataf = msg.getData().getFloat("DATA1");
//                    entries.add(new Entry(x++,dataf));
//                    mChart.postInvalidate();
//                    if(mChart.getLineData().getDataSetCount() > 0){
//                        LineDataSet tempdata = (LineDataSet) mChart.getData().getDataSetByIndex(0);
//                        tempdata.setValues(entries);
//                        mChart.getData().notifyDataChanged();
//                        mChart.notifyDataSetChanged();
//                    }
//                    break;
//                case 2:
//                    float data2 = msg.getData().getFloat("DATA2");
//                    entries2.add(new Entry(x2++,data2));
//                    mChart.postInvalidate();
//                    if(mChart.getLineData().getDataSetCount() > 1){
//                        LineDataSet tempdata = (LineDataSet) mChart.getData().getDataSetByIndex(1);
//                        tempdata.setValues(entries2);
//                        mChart.getData().notifyDataChanged();
//                        mChart.notifyDataSetChanged();
//                    }
//                    break;
//            }
//        }
//    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_collect);
        dialogAsyncTask = new DialogAsyncTask(this);
        AppContext.context = this;
        J1939Init();
        initView();
        AppContext.getModelFile().getDataSetVO().getDSItem("电量").batteryListener = this;
    }
    private void initView(){
        imageView = (ImageView) findViewById(R.id.iv_collect);
        btnStart = (Button) findViewById(R.id.btn_start_collect);
        btnStop = (Button) findViewById(R.id.btn_stop_collect);
        btnSave = (Button) findViewById(R.id.btn_collect_save);
        btnShow = (Button) findViewById(R.id.btn_collect_show);
        battery = (TextView) findViewById(R.id.tv_collect_battery);
        btnStart.setOnClickListener(this);
        btnStop.setOnClickListener(this);
        btnSave.setOnClickListener(this);
        btnShow.setOnClickListener(this);
        buffer1 = new ArrayList<>();
        buffer2 = new ArrayList<>();

        values1 = new ArrayList<>();
        values2 = new ArrayList<>();

        bufferP = new ArrayList<>();
        bufferP2 = new ArrayList<>();

        valuesP = new ArrayList<>();
        valuesP2 = new ArrayList<>();
        animationDrawable = new AnimationDrawable();
        for (int i = 1; i < 14; i++) {
            int id = getResources().getIdentifier("collecting_"+i,"drawable",getPackageName());
            Drawable drawable = getResources().getDrawable(id);
            animationDrawable.addFrame(drawable,120);
        }
        imageView.setBackground(animationDrawable);
        animationDrawable.setOneShot(false);
    }

    //初始化 1939相关线程
    private void J1939Init() {
        AppContext.initResource();
        try {
            AppContext.loadDeviceModelFile("0004","00001001");
        } catch (Exception e) {
            Log.e("MainActivity", e.toString());
            e.printStackTrace();
        }
        j1939ProtTask = new J1939_Task();
        j1939ProtTask.Init(this);
        // 启动协议任务
        j1939ProtTask.start();

        // 启动通讯任务
        j1939CommTask = new CommunicationWorker("192.168.1.178", 4001);
        Log.e("hahah","j1939CommTask start");
        j1939CommTask.start();
    }

//    public void chartinit(){
//        //设置是否可以触摸，如为false，则不能拖动，缩放等
//        mChart.setTouchEnabled(true);
//        //设置是否可以拖拽，缩放
//        mChart.setDragEnabled(true);
//        mChart.setScaleEnabled(true);
//        //设置是否能扩大扩小
//        mChart.setPinchZoom(true);
//
//        mChart.setDrawGridBackground(false);
//        XAxis xAx = mChart.getXAxis();
//        xAx.setAxisMinimum(0);
//        xAx.setGridColor(R.color.trans);
//
//        mChart.getAxisLeft().setValueFormatter(new IAxisValueFormatter() {
//            @Override
//            public String getFormattedValue(float value, AxisBase axis) {
//                BigDecimal v = new BigDecimal(value);
//                v = v.setScale(2,BigDecimal.ROUND_HALF_UP);
//                float dataf = v.floatValue();
//                return dataf+" KMP";
//            }
//        });
//
//        //设置x轴位置
//        mChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
//
//        lineData = new LineData();
//        entries = new ArrayList<>();
//        entries2 = new ArrayList<>();
//        entries.add(new Entry(0,0));
//        entries2.add(new Entry(0,0));
//        dataset = new LineDataSet(entries,"channel1");
//        dataset2 = new LineDataSet(entries2,"channel2");
//        dataset.setColor(Color.RED);
//        dataset2.setColor(Color.argb(255,139,71,38));
//        dataset.setMode(LineDataSet.Mode.CUBIC_BEZIER);
//        dataset2.setMode(LineDataSet.Mode.CUBIC_BEZIER);
//        // 显示坐标点的小圆点
//        dataset.setDrawCircles(false);
//        dataset2.setDrawCircles(false);
//        // 不显示坐标点的数据
//        dataset.setDrawValues(false);
//        dataset2.setDrawValues(false);
//        lineData.addDataSet(dataset);
//        lineData.addDataSet(dataset2);
//        mChart.setData(lineData);
//    }


    @Override
    public void onClick(View v) {
        can_Message_ts canmsg;
        switch (v.getId()){
            case R.id.btn_collect_show:
                break;
            case R.id.btn_collect_save:
                if (isCollecting){
                    Toast.makeText(this,"请先 结束 收集再保存！！",Toast.LENGTH_SHORT).show();
                }else {
                    dialogAsyncTask.execute(valuesP,valuesP2);
                }
                break;
            case R.id.btn_stop_collect:
                animationDrawable.stop();
                isCollecting = false;
                canmsg = new can_Message_ts();
                canmsg.id_u32 = 0x18ff8035;
                canmsg.format_u8 = 1;
                canmsg.numBytes_u8 = 8;
                canmsg.data_au8 = new byte[]{50,1,3,0,0,0,0,0};
                J1939_Context.j1939_CommCfg.can_TxFIFO.add(canmsg);
                break;
            case R.id.btn_start_collect:
                animationDrawable.start();
                isCollecting = true;
                canmsg = new can_Message_ts();
                canmsg.id_u32 = 0x18ff8035;
                canmsg.format_u8 = 1;
                canmsg.numBytes_u8 = 8;
                canmsg.data_au8 = new byte[]{50,1,2,0,0,0,0,0};
                J1939_Context.j1939_CommCfg.can_TxFIFO.add(canmsg);
                break;
        }
    }

    @Override
    public void onBatteryChanged(final float data) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                battery.setText("电量："+data);
            }
        });

    }


    @Override
    public void onDataChanged(Point point) {
        valuesP.add(point);
    }

    @Override
    public void onData2Changed(Point point) {
        valuesP2.add(point);
    }

    @Override
    public void onDataChangeSafeMODE(String value) {

    }

    @Override
    public void onDataNoResponse(String value, long remote, int local) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        can_Message_ts canmsg = new can_Message_ts();
        canmsg.id_u32 = 0x18ff8035;
        canmsg.format_u8 = 1;
        canmsg.numBytes_u8 = 8;
        canmsg.data_au8 = new byte[]{50,1,3,0,0,0,0,0};
        J1939_Context.j1939_CommCfg.can_TxFIFO.add(canmsg);
    }
}
